// content.js
let access_token = null;
let headers = {
	"accept": "application/json, text/plain, */*",
	"accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
	"content-type": "application/json;charset=UTF-8",
	"priority": "u=1, i",
	"sec-fetch-dest": "empty",
	"sec-fetch-mode": "cors",
	"sec-fetch-site": "same-origin",
	"x-requested-with": "1729565845731"
}
let form_code = null;

(function () {
	// 定义一个函数来添加下载按钮
	function addDownloadButton(element) {
		// 创建下载按钮元素
		var downloadButton = document.createElement('button');
		downloadButton.textContent = '下载该组件模板'; // 设置按钮文本
		downloadButton.type = 'button'; // 设置按钮类型
		downloadButton.className = 'el-button el-button--text';
		// 为下载按钮添加点击事件监听器
		downloadButton.addEventListener('click', function () {
			console.log(element.textContent);
			downloadSheetTemplate(element.textContent);
		});
		// 将下载按钮添加到目标元素的右侧
		element.parentNode.insertBefore(downloadButton, element.nextSibling);
		downloadButton.style.position = 'relative'; // 设置为相对定位
		downloadButton.style.top = '0'; // 相对于父元素顶部的位置
		downloadButton.style.right = '0'; // 相对于父元素右侧的位置
	}

	// 使用MutationObserver监听DOM变化
	document.addEventListener('DOMContentLoaded', function () {
		var targetNode = document.body; // 确保这是有效的 DOM 节点
		if (targetNode) {
			var observer = new MutationObserver(function (mutations) {
				mutations.forEach(function (mutation) {
					if (mutation.type === 'childList') {
						// 检查mutation中是否有新的节点被添加
						mutation.addedNodes.forEach(function (node) {
							if (node.id === 'tab-first') {
								addOnloadInput(node);
							}
						});
					}
				});
			});
			var config = {
				childList: true,
				subtree: true
			};
			observer.observe(targetNode, config);
		}
	});
})();

async function getToken() {
	const cookieString = document.cookie;
	// 使用split方法分割字符串，获取Manteia-token的值
	const parts = cookieString.split('Manteia-token=');
	if (parts.length > 1) {
		const tokenValue = parts[1].trim(); // 移除前后的空格
		console.log(tokenValue);
		return tokenValue;
	} else {
		console.log('Manteia-token not found');
		return null;
	}
};

async function saveToLocal(blob, fileName) {
	try {
		// 创建一个链接元素
		const url = window.URL.createObjectURL(blob);
		const a = document.createElement('a');
		a.style.display = 'none';
		a.href = url;
		// 设置下载的文件名
		a.download = fileName;
		// 触发下载
		document.body.appendChild(a);
		a.click();
		// 清理
		window.URL.revokeObjectURL(url);
		document.body.removeChild(a);

		console.log("文件下载成功:", fileName)
	} catch (error) {
		console.error('文件下载出错:', error);
	}
};

async function findComponentCodeByName(components, name) {
	// 递归函数，用于搜索组件的code
	function searchComponent(component) {
		// console.log(component.component_type_name)
		if (component.component_type_name === name && component.name === document.body.querySelector(
			"div.active > div > div > span ").innerHTML) {
			return component.code; // 找到匹配的name，返回code
		}
		if (component.children && component.children.length > 0) {
			for (let child of component.children) {
				let code = searchComponent(child); // 递归搜索子组件
				if (code) return code; // 如果在子组件中找到匹配的code，返回它
			}
		}
		return null; // 如果没有找到，返回null
	}
	// 遍历组件数组，对每个组件调用搜索函数
	try {
		for (let component of components) {
			let code = searchComponent(component);
			if (code) return code; // 如果找到匹配的code，返回它
		}
		return null;
	} catch (error) {
		console.error('获取组件code失败:', error);
		return null;
	} // 如果遍历整个数组后没有找到，返回null
}

async function downloadSheet(form_code, sheet_component_code) {
	let body = JSON.stringify({
		"form_code": form_code,
		"name": "",
		"sheet_component_code": sheet_component_code,
		"action_client_code": "PC",
		"hospital_code": "HOSPITSDZL0018465465",
		"access_token": access_token,
		"action_user_code": "USER2020042101",
		"action_user_name": "超级管理员"
	});
	const response = await fetch("/api/search_sheet_template", {
		"headers": headers,
		"referrerPolicy": "strict-origin-when-cross-origin",
		"body": body,
		"method": "POST",
		"mode": "cors",
		"credentials": "include"
	});
	let result = await response.json();
	console.log(result);
	// console.log(result['data'][0]['children']);

	let items = result['data'][0]['children'];
	for (let i = 0; i < items.length; i++) {
		let sheet_template_code = items[i]['sheet_template_code'];
		let name = items[i]['sheet_name'];
		const response = await fetch(
			`/api/download_sheet_template?sheet_template_code=${sheet_template_code}&form_code=${form_code}`, {
			"headers": {
				"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
				"accept-language": "zh-CN,zh;q=0.9",
				"content-type": "application/json;charset=UTF-8",
				"accept-encoding": "gzip, deflate, br, zstd",
				"priority": "u=0, i",
				"sec-fetch-dest": "document",
				"sec-fetch-mode": "navigate",
				"sec-fetch-site": "none"
			},
			"referrerPolicy": "strict-origin-when-cross-origin",
			"method": "GET"
		});
		result = await response.blob();
		saveToLocal(result, `${name}.xlsx`);
		// await new Promise(r => setTimeout(r, 1500));
	};
};

async function getUrlPara() {
	try {
		return window.location.href;
	} catch (error) {
		console.error('获取标签页信息失败:', error);
		return null;
	}
}

async function getQueryParams(url) {
	try {
		console.log(url)
		const urlObj = new URL(url);
		orign = urlObj.origin;
		const queryString = urlObj.hash.split('?')[1]; // 获取哈希值中的查询字符串部分
		const searchParams = new URLSearchParams(queryString);
		const params = {};
		for (let [key, value] of searchParams) {
			params[key] = value;
		}
		return params;
	} catch (error) {
		console.error('解析url失败:', error);
		return null;
	}
};

async function downloadSheetTemplate(component_name) {
	try {
		access_token = await getToken();
		// console.log(access_token);
		const params = await getUrlPara().then(url => getQueryParams(url));
		form_code = await params['code'];
		// console.log(form_code);
		var raw = JSON.stringify({
			"form_code": form_code,
			"action_client_code": "PC",
			"hospital_code": "HOSPITSDZL0018465465",
			"access_token": access_token,
			"action_user_code": "USER2020042101",
			"action_user_name": "超级管理员"
		});

		await fetch("/api/form_template_design", {
			method: 'POST',
			headers: headers,
			body: raw,
			redirect: 'follow'
		})
			.then(response => response.json())
			.then(result => findComponentCodeByName(result.data["components"], component_name))
			.then(component_code => {
				if (component_code) {
					console.log(component_code);
					downloadSheet(form_code, component_code);
				} else {
					throw new Error('获取组件code失败');
				}
			})
			.catch(error => console.log('error', error));
	} catch (error) {
		console.error('An error occurred:', error);
	}
};

async function getFormCodeByName(form_name) {
	try {
		raw = JSON.stringify({
			"name": form_name,
			"filter_code_list": [],
			"page": 1,
			"page_size": 999,
			"action_client_code": "PC",
			"hospital_code": "HOSPITSDZL0018465465",
			"access_token": access_token,
			"action_user_code": "USER2020042101",
			"action_user_name": "超级管理员"
		})
		return await fetch('/api/search_form', {
			method: 'POST',
			headers: headers,
			body: raw,
			redirect: 'follow'
		})
			.then(res => res.json())
			.then(res => res.data.data[0].code)
			.catch(error => console.log('error', error));
	} catch (error) {
		console.error('不存在该表单:', error);
	}
};

async function addForm(form_name) {
	try {
		raw = JSON.stringify({
			"name": form_name,
			"remark": "",
			"is_patient_consent": false,
			"dept_code": ["MMDptXfnEBJmSchKweIO4Q1674982171"],
			"dept_name": [],
			"action_user_name": "超级管理员",
			"action_user_code": "USER2020042101",
			"action_client_code": "PC",
			"hospital_code": "HOSPITSDZL0018465465",
			"access_token": access_token
		})
		return await fetch('/api/add_form', {
			method: 'POST',
			headers: headers,
			body: raw,
			redirect: 'follow'
		})
			.then(res => res.json())
			.then(res => {
				console.log(res.msg)
				if (res.msg !== "操作成功") {
					throw new Error(res.msg)
				}
			})
			.then(() => getFormCodeByName(form_name))
			.catch(error => console.log('error', error));
	} catch (error) {
		console.error('An error occurred:', error);
	}
}

async function updateForm(form_code, form_name, components) {
	try {
		raw = JSON.stringify({
			"form_template_dict": {
				"form_code": form_code,
				"form_name": form_name,
				"components": components
			},
			"action_client_code": "PC",
			"hospital_code": "HOSPITSDZL0018465465",
			"access_token": access_token,
			"action_user_code": "USER2020042101",
			"action_user_name": "超级管理员"
		})
		await fetch('/api/form_template_save', {
			method: 'POST',
			headers: headers,
			body: raw,
			redirect: 'follow'
		})
			.then(res => res.json())
			.then(res => res.msg)
			.catch(error => console.log('error', error));
	} catch (error) {
		console.error('An error occurred:', error);
	}
}

async function getFormDesign(form_code) {
	try {
		raw = JSON.stringify({
			"form_code": form_code,
			"action_client_code": "PC",
			"hospital_code": "HOSPITSDZL0018465465",
			"access_token": access_token,
			"action_user_code": "USER2020042101",
			"action_user_name": "超级管理员"
		})
		return await fetch('/api/form_template_design', {
			method: 'POST',
			headers: headers,
			body: raw,
			redirect: 'follow'
		})
			.then(res => res.json())
			.then(res => res.data.components)
			.catch(error => console.log('error', error));
	} catch (error) {
		console.error('An error occurred:', error);
	}
};

chrome.runtime.onMessage.addListener(
	function (request, sender, sendResponse) {
		switch (request.action) {
			case "registerPatient":
				(async () => {
					console.log("Received request from background:", request.action);
					console.log("Received data from background:", request.data);
					access_token = await getToken();
					await registerPatient(request.data.name)
						.then(pd => createTreatflow(pd))
						.catch(error => console.log('Error: ', error))
					// 向后台脚本发送响应
					sendResponse({
						response: `${request.action} success!`
					});
				})();
				break;
			case "deletePatient":
				(async () => {
					console.log("Received request from background:", request.action);
					access_token = await getToken();
					await getUrlPara()
						.then(url => getQueryParams(url))
						.then(params => deletePatient(params.pd))
						.catch(error => console.log('Error: ', error))
					// 向后台脚本发送响应
					sendResponse({
						response: `${request.action} success!`
					});
				})();
				break;
			case "downloadForm":
				(async function () {
					console.log("Received request from background:", request.action);
					access_token = await getToken();
					await getUrlPara()
						.then(url => getQueryParams(url))
						.then(params => {
							getFormDesign(params.code)
								.then(res => saveToLocal(new Blob([JSON.stringify(res)], { type: 'application/json' }), `${params.name}.form`))
						})
						.catch(error => console.log('Error: ', error))
					// 向后台脚本发送响应
					sendResponse({
						response: `${request.action} success!`
					});
				})();
				break;
			case "onloadForm":
				(async function () {
					console.log("Received request from background:", request.action);
					addOnloadInput()
						.then(element => element.click())
						.catch(error => console.log('Error: ', error));
					// 向后台脚本发送响应
					sendResponse({
						response: `${request.action} success!`
					});
				})();
				break;
			case "autoDelay":
				(async function () {
					console.log("Received request from background:", request.action);
					access_token = await getToken();
					const host = window.location.host;
					// 向后台脚本发送响应
					sendResponse({
						msg: `${request.action} success!`,
						data: {
							"access_token": access_token,
							"host": host
						}
					});
				})();
				break;
		}
	}
);

async function registerPatient(patientName) {
	headers["Cookie"] = `Manteia-access_token=${access_token}`;
	const form_code = await getFormCodeByName('基本信息');
	let data = {
		"admission_number": "87645123456",
		"name": null,
		"gender": "女",
		"id_number": "111111111111111111",
		"age": 24,
		"phone": "15999999999",
		"birthdate": "2000-01-01",
		"marital_status": "未婚",
		"patient_type": "住院",
		"contact_number": "15966666666",
		"payment_way": [
			"商业医保"
		],
		"COMPONTQIRoJqCnZfcyD4U1656063503": [
			"GROUPXV9AB57kEtlGR1rvD1666056428",
			"USERXX1kjATYUZyX04f8ip1666171234"
		],
		"social_security_card_no": "123465648916",
		"patient_id": "48156516",
		"visit_number": "651328653",
		"visit_sn": "457865562",
		"visit_times": 1,
		"hospitalization_times": 1,
		"past_medical_history": "1"
	};
	data.name = patientName;
	const components = await getFormDesign(form_code).then(cs => writeForm(cs, data)).catch(error => console.log("Error: ", error));
	console.log(components);

	const head_img = "/mriaapi/get_patient_image?file_id=66f8ca6bed83d7f9b6fafa40";

	var raw = JSON.stringify({
		"face_id": "",
		"head_img": head_img,
		"form_template": {
			"form_code": form_code,
			"components": components,
			"version": 0
		},
		"register_code": "",
		"action_client_code": "PC",
		"hospital_code": "HOSPITSDZL0018465465",
		"access_token": `${access_token}`,
		"action_user_code": "USER2020042101",
		"action_user_name": "超级管理员"
	});

	const response = await fetch(`/mriaapi/add_visit_info`, {
		method: 'POST',
		headers: headers,
		body: raw,
		redirect: 'follow'
	}).then(res => res.json());
	console.log(response)
	let pd = await response['data']['base_info']
	return await pd;
};

async function deletePatient(patient_visit_code) {
	var raw = JSON.stringify({
		"patient_name": "",
		"patient_visit_code": patient_visit_code,
		"action_client_code": "PC",
		"hospital_code": "HOSPITSDZL0018465465",
		"access_token": access_token,
		"action_user_code": "USER2020042101",
		"action_user_name": "超级管理员"
	});

	fetch("/mriaapi/delete_patient_visit", {
		method: 'POST',
		headers: headers,
		body: raw,
		redirect: 'follow'
	})
		.then(response => response.json())
		.then(result => console.log(result))
		.catch(error => console.log('error', error));
}

async function createTreatflow(pd) {
	headers["Cookie"] = `Manteia-access_token=${access_token}`;
	let data = {
		"COMPONR06KhCL27MHiseV51705476085": [
			[
				"头颈部",
				"鼻咽"
			]
		],
		"sick_type_code": "原发",
		"flow_code": "FLOWXXwt2KHYlkzEMyOrFs1683365500",
		"treat_aim": "",
		"reason": "首程治疗",
		"diagnoses": "鼻咽恶性肿瘤",
		"tnm_component": {},
		"combine_stage": "",
		"stage_accord": "",
		"remarks": ""
	}

	const form_code = await getFormCodeByName('程/段信息')
	const components = await getFormDesign(form_code).then(cs => writeForm(cs, data));
	console.log(components);

	let body = JSON.stringify({
		"patient_visit_code": pd,
		"is_send": 0,
		"form_template": {
			"form_code": form_code,
			"form_name": "程/段信息",
			"is_must": true,
			"components": components,
			"version": 130,
			"is_has_template": false
		},
		"action_client_code": "PC",
		"hospital_code": "HOSPITSDZL0018465465",
		"access_token": access_token,
		"action_user_code": "USER2020042101",
		"action_user_name": "超级管理员"
	})
	await fetch(`/mriaapi/save_treatflow_info`, {
		method: 'POST',
		headers: headers,
		body: body,
		redirect: 'follow'
	})
		.then(response => response.json())
		.then(result => console.log(result))
		.catch(error => console.log('error', error));
}

async function writeForm(components, data) {
	try {
		function traverse(component, data) {
			if (component && typeof component === 'object') {
				if (Object.keys(data).includes(component.code)) {
					console.log("找到一个组件：", component.code, data[component.code])
					component["value"] = data[component.code]
				}
				if (component.children && component.children.length > 0) {
					component.children.forEach(child => traverse(child, data)); // 递归子元素
				}
			}
		}
		if (components && components.length > 0) {
			for (let component of components) {
				traverse(component, data);
			}
		} else {
			console.log("TypeError: components is not iterable", components)
		}
		return components;
	} catch (error) {
		console.error("Error:", error)
	}
}

async function addOnloadInput() {
	try {
		// 创建下载按钮元素
		if (!document.getElementById("onload-files")) {
			var onloadInput = document.createElement('input');
			onloadInput.type = 'file'
			onloadInput.id = "onload-files"
			onloadInput.addEventListener("change", function () {
				var selectedFile = document.getElementById("onload-files").files[0]; //获取读取的File对象
				var name = selectedFile.name.split('.form')[0];; //读取选中文件的文件名
				var size = selectedFile.size; //读取选中文件的大小
				console.log("文件名:" + name + "大小：" + size);
				var reader = new FileReader(); //这里是核心！！！读取操作就是由它完成的。
				reader.readAsText(selectedFile); //读取文件的内容
				reader.onload = function () {
					console.log("读取结果：", this.result);
					const components = this.result;
					//当读取完成之后会回调这个函数，然后此时文件的内容存储到了result中。直接操作即可。
					(async function () {
						access_token = await getToken();
						await addForm(name)
							.then(code => {
								if (code) {
									updateForm(code, name, JSON.parse(components))
								} else {
									throw new Error("新增表单失败")
								}
							})
							.catch(error => console.log('Error: ', error))
					})();
				};
			}, false);
			document.body.appendChild(onloadInput);
			return onloadInput;
		} else {
			return document.getElementById("onload-files");
		}
	} catch (error) {
		console.error('An error occurred:', error);
	}
}